//
//  HomeTableViewController.swift
//  WeiBo_Private
//
//  Created by Yangperlove on 16/1/10.
//  Copyright © 2016年 Yangperlove. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
class HomeTableViewController: BaseViewController {
    
    //模型数据
    private lazy var statusList = [Status]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        visitor?.setupUIWithInfo(nil, tipText: "关注一些人，回这里看看有什么惊喜")
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
        if tableView != nil {
        tableView.registerClass(StatusCell.self, forCellReuseIdentifier: "HomeCell")
        
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 300
        tableView.tableFooterView = indicatorView
            
        self.tableView.reloadData()
        }
        
        refreshControl = UIRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: .ValueChanged)
        
        //加载首页数据
        loadData()
        
    }
    
    func loadData() {
        let AFN = AFHTTPSessionManager()
        guard let access_token = UserAccountViewModel().access_token else {
//            SVProgressHUD.showErrorWithStatus("数据结构错误")
            print("数据结构错误")
            return
        }
        var params = ["access_token":access_token]
        
        var since_id: Int64 = 0
        var max_id: Int64 = 0
        if indicatorView.isAnimating() {
            //上拉加载更多数据
            max_id = self.statusList.last?.id ?? 0
        } else {
            //下拉刷新
            since_id = self.statusList.first?.id ?? 0
        }
        
        if since_id > 0 {
            params["since_id"] = "\(since_id)"
        }
        
        if max_id > 0 {
            params["max_id"] = "\(max_id - 1)"
        }
        
        
        AFN.GET("https://api.weibo.com/2/statuses/home_timeline.json", parameters: params, progress: nil, success: { (_, result) -> Void in
//            print(result)
            
            guard let dict = result else {
                print("result字典数据错误")
                return
            }
            
            guard let array = dict["statuses"] as? [[String : AnyObject]] else {
                print("array数据结构错误")
                return
            }
            
            //定义可变数组
            var tempArr = [Status]()
            for tmp in array {
                let status = Status(dict: tmp)
                tempArr.append(status)
            }
            
            print("\(tempArr.count)" + "-----")
            if since_id > 0 {
            self.statusList = tempArr + self.statusList
            } else if max_id > 0 {
                self.statusList = self.statusList + tempArr
                self.indicatorView.stopAnimating()
            } else {
                self.statusList = tempArr
            }
            self.tableView.reloadData()
            self.refreshControl?.endRefreshing()
            
            }) { (_, error) -> Void in
                print(error)
        }
    }
    
    lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
}



extension HomeTableViewController {
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("HomeCell", forIndexPath: indexPath) as! StatusCell
        cell.status = statusList[indexPath.row]
        
        if indexPath.item == statusList.count - 2 && !indicatorView.isAnimating(){
            indicatorView.startAnimating()
            loadData()
        }
        return cell
    }
}
